<template>
   <div class="upload-img-component">
        <div class="img-item" v-for="(item,index) in imgs.list" :key="index">
            <img :src="`${baseUrl}${item}`"/>
            <div class="options">
                <el-icon class="avatar-view-icon" @click="view(item)"><ZoomIn /></el-icon>
                <el-icon class="avatar-remove-icon" @click="remove(index)"><Delete /></el-icon>
            </div>
        </div>
        <el-upload
            v-if="props.type==='even'||imgs.list.length===0"
            :action="`${baseUrl}${imageUrl}`"
            :show-file-list="false"
            :headers="{Authorization:`Bearer ${token}`}"
            :data="{type:props.dir}"
            :on-success="uploadSuccess"
            :on-error="uploadError"
        >
            <div class="up-img">
                <el-icon class="avatar-uploader-icon"><Plus /></el-icon>
            </div>
        </el-upload>
        <el-dialog v-model="dialogVisible">
            <img style="width:100%;" w-full :src="dialogImageUrl" alt="预览图片" />
        </el-dialog>
   </div>
</template>



<script setup lang="ts">
import {ref,reactive,toRaw,watch} from 'vue'
import type { UploadProps } from 'element-plus'
import {imageUrl} from '/@/api/upload'
import { Plus,ZoomIn,Delete } from '@element-plus/icons-vue'
import { Local } from '/@/utils/storage'
import { ElNotification } from 'element-plus'
import router from '/@/router'
import _ from 'lodash'

interface Props {
    dir: string
    type: string
    modelValue: string[]|string
}

const props = withDefaults(defineProps<Props>(), {
    dir: '',
    type: 'odd',
    modelValue:()=>{
        return []
    }
})

const baseUrl: string = import.meta.env.VITE_AXIOS_BASE_URL as string
const token = Local.get('token')
interface headType {
   list:string[]
}
const imgs = reactive<headType>({
    list:[]
})
const dialogImageUrl = ref('')
const dialogVisible = ref(false)
const emit = defineEmits(['update:modelValue'])
const handleChange = () => {
    emit('update:modelValue',props.type === 'odd'?toRaw(imgs.list)[0]||'':imgs)
}

const uploadSuccess: UploadProps['onSuccess'] = (response) => {
  if(response.code===200){
    imgs.list.push(response.data as never)
    handleChange()
  }else if(response.code===401){
    ElNotification({
        type: 'error',
        message: '请登录',
    })
    router.push({ name: 'login' })
  }else{
    ElNotification({
        message: response.message,
        type: 'error'
    })
  }
}

const uploadError: UploadProps['onError'] = () => {
  ElNotification({
    message: '上传失败',
    type: 'error'
  })
}


const view = (url:string) => {
    dialogImageUrl.value = `${baseUrl}${url}`
    dialogVisible.value = true
}

const remove = (index:number) => {
    imgs.list.splice(index,1)
    handleChange()
}
imgs.list = props.type === 'odd'?reactive(props.modelValue?[props.modelValue] as string[]:[]):reactive(_.cloneDeep(props.modelValue) as string[])
watch(()=>props.modelValue, () => {
    imgs.list = props.type === 'odd'?reactive(props.modelValue?[props.modelValue] as string[]:[]):reactive(_.cloneDeep(props.modelValue) as string[])
})

</script>

<style lang="scss">
    .upload-img-component{
        display:flex;
        flex-wrap:wrap;
        .img-item{
            cursor: pointer;
            width:120px;
            height:120px;
            position:relative;
            margin:0 15px 15px 0;
            &:hover{
                .options{
                    display:flex;
                }
            }
            >img{
                width:100%;
                height:100%;
                object-fit: cover;
            }
            .options{
                display:none;
                position:absolute;
                left:0;
                top:0;
                width:100%;
                height:100%;
                color:#fff;
                font-size:21px;
                justify-content:space-around;
                align-items:center;
                background:rgba(0,0,0,.5);
            }
        }
        .up-img{
            cursor: pointer;
            width:120px;
            height:120px;
            display:flex;
            justify-content:center;
            align-items:center;
            border:1px dashed #999;
            margin-bottom:15px;
            &:hover{
                color:rgb(64, 158, 255);
                border-color:rgb(64, 158, 255);
            }
        }
        .avatar-uploader-icon{
            font-size:30px;
        }
    }
</style>